<template>
  <!--名单剔除 客户/账户/查看-->
  <section class="component modify-role paddingLeft">
    <el-form :model="addModel" :rules="rules" ref="form" label-width="90px" class="tableInput">
      <el-row>基础信息展示：</el-row>
      <el-row v-if="hidden">
        <el-col :span="12">
          <el-form-item label="账户号：">{{ addModel.caseNumber }}
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12">
          <el-form-item label="还款日：">{{ $filter.dateFormat(addModel.payDate) }}
          </el-form-item>
        </el-col> -->
        <el-col :span="12">
          <el-form-item label="还款日：">{{ addModel.payDate }}
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="客户姓名：">{{ addModel.personalName }}
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户号：">{{ addModel.personalNo }} </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="!hidden">
        <el-col>客户名下账户信息：</el-col>
        <el-col>
          <data-box :data="customerLists" class="widthCenter">
            <template slot="columns">
              <el-table-column prop="caseNumber" label="账户号" :min-width="$helper.getColumnWidth(5)" show-overflow-tooltip>
              </el-table-column>
              <el-table-column prop="productType" label="产品类型" :min-width="$helper.getColumnWidth(5)" show-overflow-tooltip>
              </el-table-column>
              <el-table-column prop="overduePeriod" label="逾期阶段" :min-width="$helper.getColumnWidth(5)" show-overflow-tooltip>
                <template slot-scope="scope">{{
                  `${scope.row.overduePeriod}`
                    ? `M${scope.row.overduePeriod}`
                    : ""
                }}</template>
              </el-table-column>
              <el-table-column prop="overdueAmount" label="逾期金额" :min-width="$helper.getColumnWidth(5)" show-overflow-tooltip>
              </el-table-column>
            </template>
          </data-box>
        </el-col>
      </el-row>
      <el-row>
        <el-col>剔除规则设置：</el-col>
        <el-col v-if="!disabled">
          <el-col :span="12" v-if="!hidden">
            <el-form-item label="账户选择" align="left" prop="account">
              <el-select v-model="addModel.account" :disabled="disabled">
                <el-option v-for="{ index, caseNumber } in accounts" :key="index" :value="caseNumber" :label="caseNumber">{{ caseNumber }}</el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="剔除渠道" align="left" prop="channel">
              <el-select v-model="addModel.channel" :disabled="disabled">
                <el-option v-for="{ index, name, code } in $dict.getDictData(
                  'ChannelType'
                )" :key="index" :label="name" :value="code"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="剔除类型" align="left" prop="strategyEliminateType">
              <el-select v-model="addModel.strategyEliminateType" :disabled="disabled||channelDisabled" @change="onchange">
                <el-option v-for="{ index, name, code } in $dict.getDictData(
                  'StrategyEliminateType'
                )" :key="index" :label="name" :value="code"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="有效日期" prop="expiryDate">
              <el-date-picker v-model="addModel.expiryDate" type="datetime" placeholder="选择日期" default-time="23:59:59" :disabled="disabled">
              </el-date-picker>
              <el-button style="margin-left:10px" @click="updata" :disabled="disabled">添加</el-button>
            </el-form-item>
          </el-col>
        </el-col>
      </el-row>
      <from-base v-model="channelJsons" :showIn="showIn" class="widthCenterTwo" :flag="!hidden" :deleDisbled="disabled"></from-base>
      <el-row>
        <el-form-item label="策略状态" prop="strategyState">
          <el-select v-model="addModel.strategyState" placeholder="请选择" :disabled="disabled">
            <el-option v-for="{ index, name, code } in $dict.getDictData('CommonState')" :key="index" :label="name" :value="code"></el-option>
          </el-select>
        </el-form-item>
      </el-row>
      <el-row>
        <el-form-item label="剔除原因" label-width="90px" prop="remark">
          <el-col class="widthPublic">
            <el-input type="textarea" v-model="addModel.remark" :rows="3" :maxlength="500" :disabled="disabled" show-word-limit></el-input>
          </el-col>
        </el-form-item>
      </el-row>
      <el-row v-if="showRke">
        <el-row v-if="!history">
          <el-col class="widthFour">队列历史注记</el-col>
          <el-col class="widthThree">
            <data-box :data="historyNotes" :page="pageService" class="marginTL">
              <template slot="columns">
                <el-table-column prop="timeCreated" label="注记时间" :formatter="row => $filter.dateTimeFormat(row.timeCreated)" :min-width="$helper.getColumnWidth(5)" show-overflow-tooltip>
                </el-table-column>
                <el-table-column prop="operatorRealName" label="添加人" :min-width="$helper.getColumnWidth(5)" show-overflow-tooltip>
                </el-table-column>
                <el-table-column prop="remark" label="内容" :min-width="$helper.getColumnWidth(5)" show-overflow-tooltip>
                </el-table-column>
              </template>
            </data-box>
          </el-col>
        </el-row>
        <el-row v-else>
          <el-col>
            <el-form-item label="申请人">{{ addModel.operatorRealName }}
            </el-form-item>
          </el-col>
          <el-col class="widthSix">审批历史</el-col>
          <el-col class="widthPublic">
            <data-box :data="approvalHistory" class="paddingNone">
              <template slot="columns">
                <el-table-column prop="approvalRealName" label="审批人" :min-width="$helper.getColumnWidth(5)" show-overflow-tooltip>
                </el-table-column>
                <el-table-column prop="approvalTime" label="审批时间" :formatter="row => $filter.dateTimeFormat(row.approvalTime)" :min-width="$helper.getColumnWidth(5)" show-overflow-tooltip>
                </el-table-column>
                <el-table-column prop="applyStatus" label="审批结果" :formatter="
                    row => $filter.dictConvert(row.applyStatus, 'ApplyStatus')
                  " :min-width="$helper.getColumnWidth(5)" show-overflow-tooltip>
                </el-table-column>
                <el-table-column prop="approvalOpinion" label="审批意见" :min-width="$helper.getColumnWidth(5)" show-overflow-tooltip>
                </el-table-column>
              </template>
            </data-box>
          </el-col>
        </el-row>
      </el-row>
    </el-form>
    <div class="operate-buttons" v-if="disabled">
      <el-button @click="close">关闭</el-button>
    </div>
    <div class="operate-buttons" v-else>
      <el-button @click="close">取消</el-button>
      <el-button @click="commit">{{`${operationType.DEFAULT==='OPERATION_EDIT'?'提交审批':'保存'}`}}</el-button>
    </div>
  </section>
</template>

<script lang="ts">
import Vue from "vue";
import Component from "vue-class-component";
import { Dependencies } from "~/core/decorator";
import { State, Getter, Action } from "vuex-class";
import FromBase from "./from-base.vue";
import { Emit, Prop, Watch } from "vue-property-decorator";
import ExpressionBase from "./expression-base.vue";
import { PageService } from "~/utils/page.service";
import { OPERATION_TYPE } from "~/config/enum.config";
import { ListRemovedService } from "~/services/domain-service/list-removed.service";
import { IstrategyInfo, FormItem } from "~/components/system-manage/strategy-config/strategy-helper.config";

@Component({
  components: { FromBase, ExpressionBase }
})
export default class AddListItem extends Vue {
  @Dependencies(PageService)
  private pageService: PageService;
  @Dependencies(ListRemovedService)
  private listRemovedService: ListRemovedService;

  @Prop({ type: Object })
  private roleData: any;
  // 页面按钮类型
  private operationType: any = OPERATION_TYPE
  private hidden: boolean = true;
  private addModel: any = {
    caseNumber: "",
    customerNo: "",
    personalNo: '',
    payDate: "",
    personalName: "",
    channel: "",
    expiryDate: "",
    strategyType: '',
    account: [],
    strategyState: '',
    strategyEliminateType: ''
  };
  private showIn = false;
  private showRke = false;
  private disabled = false;
  private history = false;
  private channelDisabled: boolean = false
  private accounts: any = [];
  private customerLists: any = []
  private historyNotes: any = [];
  private approvalHistory: any = [];
  private channelJsons: any = [];
  private rules: any = {};
  @Emit("refreshList")
  public refreshList () { }
  @Emit("close")
  public close () { }
  /**
   * 剔除类型监听
   */
  private onchange (v) {
    v ? this.$set(this.addModel, 'strategyEliminateType', v) : this.$set(this.addModel, 'strategyEliminateType', '')
  }
  /**
   * 剔除渠道和剔除类型联动
   */
  @Watch('addModel.channel')
  private change (v) {
    if (!v) return
    const channelList = ['ALL', 'SELF', 'OUTER', 'LAWSUIT', 'ROBOT']
    const item = channelList.find(f => f === v)
    this.onchange(!!item)
    if (item) {
      this.channelDisabled = true
      this.addModel.strategyEliminateType = 'AUTO_ELIMINATE'
    } else {
      this.channelDisabled = false
      // this.$set(this.addModel, 'strategyEliminateType', '')
    }
  }

  private get strategyDataSet () {
    if (!this.addModel.formulaJson) return [];
    return JSON.parse(this.addModel.formulaJson) as IstrategyInfo[];
  }

  private set strategyDataSet (value) {
    this.addModel.formulaJson = JSON.stringify(value);
  }
  private updata () {
    const account = this.addModel.account;
    const channel = this.addModel.channel;
    const expiry = this.addModel.expiryDate;
    const strategyEliminateType = this.addModel.strategyEliminateType
    if (this.addModel.strategyType === 'CUSTOMER') {
      if (!channel || !expiry || !account || !strategyEliminateType) {
        this.$message.warning("请完善剔除规则！");
        return false;
      } else {
        this.channelJsons.push({
          caseNumber: this.addModel.account,
          channelType: this.addModel.channel,
          effectiveTime: this.addModel.expiryDate,
          strategyEliminateType: this.addModel.strategyEliminateType
        });
        this.addModel.account = ''
      }
    } else {
      if (!channel || !expiry || !strategyEliminateType) {
        this.$message.warning("请完善剔除规则！");
        return false;
      } else {
        this.channelJsons.push({
          channelType: this.addModel.channel,
          effectiveTime: this.addModel.expiryDate,
          strategyEliminateType: this.addModel.strategyEliminateType
        });
      }
    }
    this.channelDisabled = false
    this.addModel.channel = ''
    this.addModel.expiryDate = ''
    this.addModel.strategyEliminateType = "";
  }
  private reset () {
    const from: any = this.$refs["form"];
    from.resetFields();
    this.channelDisabled = false
    this.pageService.pageSize = 10
    this.pageService.pageSizeOpts = [10, 20, 30]
    this.addModel = { ...this.roleData, strategyState: this.roleData.strategyState === 'DISABLED' ? 'DISABLED' : 'ENABLED' };
    this.channelJsons = []
    this.customerLists = []
    this.accounts = []
    // 查看/审批日志查看 页面禁灰
    this.operationType.DEFAULT === 'OPERATION_SEE' || this.operationType.DEFAULT === 'APPROVAL_LOG' ? this.disabled = true : this.disabled = false;
    // 页面为新增时 历史注记/审批历史显示设置
    this.operationType.DEFAULT === 'ACCOUNT_ELIMINATION' || this.operationType.DEFAULT === 'CUSTOMER_ELIMINATION' ? this.showRke = false : this.showRke = true
    // 页面为审批查看时 历史注记显示设置
    if (this.operationType.DEFAULT === 'APPROVAL_LOG') {
      this.history = true
      this.commonFunction()
      // 审批日志 
      this.addModel.applyId ? this.listApprovalLog() : this.approvalHistory = [];
    } else { this.history = false; }
    // 账/客户查询 
    if (this.operationType.DEFAULT === "ACCOUNT_ELIMINATION") this.accountList();
    if (this.operationType.DEFAULT === "CUSTOMER_ELIMINATION") this.customerList();
    // 查看/编辑
    if (this.operationType.DEFAULT === 'OPERATION_EDIT' || this.operationType.DEFAULT === 'OPERATION_SEE') { this.commonFunction() }



    this.listHistoryNotes()

  }
  /**
   * @description: 
   * @param {*}
   */
  private commonFunction () {
    console.log('this.roleData', this.roleData);

    this.roleData.strategyType === 'ACCOUNT' ? this.accountList() : this.customerList();
    this.addModel.channel = ''
    this.channelJsons = JSON.parse(this.addModel.channelJson)
  }
  /**
   * 根据客户号查询帐户信息
   */
  private customerList () {
    this.hidden = false
    this.listRemovedService.findCustomerNo(this.addModel).subscribe(data => {
      this.addModel.personalName = data[0].personalName
      this.addModel.customerNo = data[0].personalNo
      this.addModel.personalNo = data[0].personalNo
      this.customerLists = data
      data.map(f => {
        this.accounts.push({ caseNumber: f.caseNumber })
      })
      this.addModel.strategyType = 'CUSTOMER'
    })
  }
  /**
   * 根据账户号查询账户信息
   */
  private accountList () {
    this.hidden = true;
    this.listRemovedService.findCaseInfo(this.addModel).subscribe(data => {
      console.log('data', data, this.roleData);
      this.addModel = { ...this.roleData, ...data, strategyState: this.roleData.strategyState === 'DISABLED' ? 'DISABLED' : 'ENABLED' }
      console.log('addModel', this.addModel);
      if (this.addModel.channelJson) this.channelJsons = JSON.parse(this.addModel.channelJson);
      this.addModel.customerNo = this.addModel.personalNo
      this.addModel.strategyType = 'ACCOUNT'
    })
  }
  /**
   * 队列历史注记
   */
  private listHistoryNotes () {
    const modelId = { id: this.addModel.id };
    this.listRemovedService
      .getNameLogList(modelId, this.pageService)
      .subscribe(data => {
        this.historyNotes = data;
      });
  }

  /**
   * 审批日志
   */
  private listApprovalLog () {
    const applyId = { id: this.addModel.id };
    this.listRemovedService.findNameHistory(applyId).subscribe(data => {
      this.approvalHistory = data;
    });
  }
  /**
   * 提交验证并并与数据库交互
   */
  private commit () {
    console.log('channelJsons', this.channelJsons);
    if (!this.channelJsons.length) {
      this.$message.warning("请添加剔除规则!");
      return
    }

    this.addModel.channelJson = JSON.stringify(this.channelJsons);
    const Form: any = this.$refs["form"];
    Form.validate(valid => {
      if (!valid) return;
      this.listRemovedService.saveNameList(this.addModel).subscribe(data => {
        this.$message.success("新增成功!");
        this.channelJsons = [];
        this.refreshList();
        this.close();
      });
    });
  }
}
</script>

<style lang="less" scoped>
.paddingLeft {
  padding-left: 30px !important;
}
.paddingNone {
  padding: 0 !important;
}
.marginTL {
  margin: -10px 0 0 -10px !important;
}
.widthCenter {
  width: 690px !important;
  margin-left: 80px !important;
}
.widthCenterTwo {
  width: 692px !important;
  margin: 10px auto auto 89px !important;
}
.widthThree {
  width: 700px !important;
}
.widthFour {
  width: 90px !important;
}
.widthSix {
  width: 90px !important;
  text-align: center !important;
}
.widthPublic {
  width: 690px;
}
</style>
